package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/13 9:31
 */
public class Flink01_Batch_WC {
    public static void main(String[] args) throws Exception {
        // 1. 创建批的执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 从数据源(source)读取数据, 得到数据集
        DataSource<String> source = env.readTextFile("input/words.txt");
        // 3. 各种转换
        FlatMapOperator<String, String> words = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value,
                                Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });
    
        MapOperator<String, Tuple2<String, Long>> wordAndOne = words.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
        
        });
    
        AggregateOperator<Tuple2<String, Long>> result = wordAndOne
            .groupBy(0)
            .sum(1);
    
        // 4. 输出(sink)
        result.print();
        
    }
}
/*
1. 创建上下文

2. 从数据源读取数据, 得到一个rdd

3. 对rdd做各种转换

4. 执行行动算子 (collect)

5. 启动上下文

 */